package guutil

import (
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"gitee.com/MikeDDD/gu/logs"
)

var httpCli = &http.Client{Timeout: time.Second * 3}

func Post(path, jsonBody string, header map[string]string) (string, bool, int) {
	logs.Debug("requ: %v, %v", path, string(jsonBody))
	req, err := http.NewRequest("POST", path, strings.NewReader(jsonBody))
	if err != nil {
		logs.Error(err)
		return "", false, 0
	}
	for k, v := range header {
		req.Header.Add(k, v)
	}

	resp, err := httpCli.Do(req)
	if err != nil {
		logs.Warn(err)
		return "", false, 0
	}
	defer resp.Body.Close()

	respData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error(err)
		return "", false, 0
	}

	logs.Debug("resp: %v, %v", resp.StatusCode, string(respData))

	return string(respData), true, resp.StatusCode
}

func Get(path string, header map[string]string) (string, bool) {
	logs.Debug("requ: %v", path)
	req, err := http.NewRequest("GET", path, nil)
	if err != nil {
		logs.Error(err)
		return "", false
	}

	for k, v := range header {
		req.Header.Add(k, v)
	}

	resp, err := httpCli.Do(req)
	if err != nil {
		logs.Warn(err)
		return "", false
	}
	defer resp.Body.Close()

	respData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error(err)
		return "", false
	}

	logs.Debug("resp: %v, %v", resp.StatusCode, string(respData))

	return string(respData), true
}
